# field_management/models.py
from django.db import models
from django.contrib.auth.models import User # Import User model
from django.urls import reverse

class Field(models.Model):
    """代表一个地块/田块"""
    owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="负责人")
    name = models.CharField(max_length=100, verbose_name="田块名称/编号")
    location = models.CharField(max_length=255, blank=True, null=True, verbose_name="位置描述")
    latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, verbose_name="纬度")
    longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, verbose_name="经度")
    area = models.DecimalField(max_digits=10, decimal_places=2, help_text="单位：亩", verbose_name="面积")
    soil_type = models.CharField(max_length=100, blank=True, null=True, verbose_name="土壤类型")
    irrigation_source = models.CharField(max_length=100, blank=True, null=True, verbose_name="灌溉来源")
    notes = models.TextField(blank=True, null=True, verbose_name="备注")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return f"{self.name} ({self.owner.username})"

    def get_absolute_url(self):
        # Used by CreateView and UpdateView upon success
        return reverse('field_management:field_detail', kwargs={'pk': self.pk})

    class Meta:
        verbose_name = "田块信息"
        verbose_name_plural = "田块信息"
        ordering = ['-created_at']